import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import style from './index.module.less'
import classNames from 'classnames'
import { initListRequest } from './ajax'
import $ from 'jquery'
import { awaitWrap, formatDate, getFilePath } from '@src/assets/js/tool'
import { useAppSelector } from '@src/redux/hook'
import PageEmpty from '@components/pageEmpty'
import { SpinLoading } from 'antd-mobile'

async function loadBefore (
  currentCase,
  person,
  list,
  containerRef,
  setList,
  setHasHistory,
  setLoading
) {
  setLoading(true)
  const condition = [{ k: 'delivered_datetime', o: '<', v: list[0].delivered_datetime }]
  const [e, d] = await awaitWrap(initListRequest(currentCase.id, person.accountid, condition))
  setLoading(false)
  if (e === null && d !== null) {
    const c = containerRef.current
    let sh = 0
    if (c !== null) {
      sh = c.scrollHeight
    }
    setList([...d.list, ...list])
    setHasHistory(d.total > 20)
    setTimeout(() => {
      if (c !== null) {
        c.scrollTop = c.scrollHeight - sh
      }
    }, 0)
  }
}

async function loadNew (
  currentCase,
  person,
  list,
  containerRef,
  setList
) {
  if (currentCase === null || person === null) {
    return undefined
  }
  const condition = []
  if (list.length > 0) {
    condition.push({ k: 'delivered_datetime', o: '>', v: list[list.length - 1].delivered_datetime })
  }
  const [e, d] = await awaitWrap(initListRequest(currentCase.id, person.accountid, condition, 30 * 1000))
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTimeout(() => {
      const c = containerRef.current
      if (c !== null && d.list.length > 0) {
        $(c).animate({ scrollTop: c.scrollHeight })
      }
    }, 0)
  }
}

async function initData (
  currentCase,
  person,
  containerRef,
  setList,
  setHasHistory,
  setAfterLoading
) {
  setAfterLoading(true)
  setList([])
  const [e, d] = await awaitWrap(initListRequest(currentCase.id, person.accountid))
  setAfterLoading(false)
  if (e === null && d !== null) {
    setList(d.list)
    setHasHistory(d.total > 20)
    setTimeout(() => {
      const c = containerRef.current
      if (c !== null) {
        $(c).animate({ scrollTop: c.scrollHeight })
      }
    }, 0)
  }
}

function Item ({ data }) {
  const userInfo = useAppSelector((state) => state.basic.userInfo)
  const file = useMemo(() => {
    if (data.file instanceof Array && data.file.length > 0) {
      return data.file[0]
    }
    return null
  }, [data])
  const self = useMemo(() => {
    return data.operatorid === userInfo.id
  }, [data, userInfo])
  const n = useMemo(() => {
    if (typeof data.operator === 'string' && data.operator.length > 0) {
      return data.operator[0]
    }
    return '无'
  }, [data])
  return (
    <div className={classNames(style.item, { [style.self]: self })}>
      <div className={style.label}>
        <span>{n}</span>
      </div>
      <div className={style.content}>
        {
          file !== null
            ? (
              <a href={getFilePath(file)} target='_blank' rel='noreferrer'>
                <span className={style['file-name']}>{file.original_filename !== undefined ? file.original_filename : file.filename}</span>
              </a>
            )
            : (
              <div dangerouslySetInnerHTML={{ __html: data.content }} />
            )
        }
        <div className={style.date}>{formatDate(data.delivered_datetime, 'YYYY-MM-DD HH:mm:ss')}</div>
      </div>
    </div>
  )
}

function Inner (props, ref) {
  const containerRef = useRef(null)
  const currentCase = useAppSelector(state => state.chart.currentCase)
  const person = useAppSelector(state => state.chart.currentPerson)
  const [list, setList] = useState([])
  const [hasHistory, setHasHistory] = useState(false)
  const [afterLoading, setAfterLoading] = useState(true)
  const [beforeLoading, setBeforeLoading] = useState(false)
  useEffect(() => {
    if (currentCase !== null && person !== null) {
      initData(currentCase, person, containerRef, setList, setHasHistory, setAfterLoading).then(null, null)
    }
  }, [currentCase, person])

  useImperativeHandle(ref, () => {
    return {
      loadMore: () => {
        if (currentCase && person) {
          loadNew(currentCase, person, list, containerRef, setList).then(null, null)
        }
      }
    }
  })
  if (currentCase === null || person === null) {
    return <span />
  }
  return (
    <div className={style.container} ref={containerRef}>
      {
        !afterLoading && list.length === 0 && (
          <PageEmpty />
        )
      }
      {beforeLoading && (
        <div className={style.loading}><SpinLoading  style={{ '--size': '1rem' }} /></div>
      )}
      {
        !beforeLoading && !afterLoading && hasHistory && (
          <div className={style['add-history']}>
            <a onClick={() => {
              loadBefore(currentCase, person, list, containerRef, setList, setHasHistory, setBeforeLoading).then(null, null)
            }}
            >加载更多
            </a>
          </div>
        )
        }
      {
        list.map(li => <Item key={li.id} data={li} />)
      }
      {afterLoading && <div className={style.loading}><SpinLoading  style={{ '--size': '1rem' }} /></div>}
    </div>
  )
}

const InnerComponent = forwardRef(Inner)

function Main () {
  const ref = useRef(null)
  const version = useAppSelector(state => state.chart.loadMoreVersion)
  useEffect(() => {
    let timer
    function loop () {
      if (ref.current !== null) {
        ref.current.loadMore()
      }
      timer = setTimeout(() => { loop() }, 30 * 1000)
    }
    timer = setTimeout(() => {
      loop()
    }, 10000)
    return () => {
      timer && clearTimeout(timer)
    }
  }, [ref])
  useEffect(() => {
    if (ref.current !== null) {
      ref.current.loadMore()
    }
  }, [version, ref])
  return (
    <InnerComponent ref={ref} />
  )
}

export default Main
